<?php 
class Pages_Model_Behavior extends Zen_Behavior_Model 
{
	public function afterChange($params) {
		$this->updatePath ();
		return $params;
	}
	
	protected function updatePath() {
		$data =  $this->getModel()->select ()->setColumns ( array ('tree' => array ('id', 'parent_id', 'left', 'right','level' ), 'item' => array ('alias', 'label' ) ) )->setOrder('tree.left')->setDepth ( 0 )->getData ();
		$alias = array();
		
		$types=$this->getModel()->getTypes();
		$ItemModel = $types['item'] ['model'];
		
		foreach ( $data as $node ) {
			ksort( $alias, SORT_NUMERIC );
			$level = $node['level'];
			if ( isset($alias[$level]) ) {
				$count = count($alias);
				for ($i = $level; $i<=$count; $i++ ) {
					unset ($alias[$i]);
				}
			}
			$alias[$level]=$node['alias'];
			$aliasfull="/".implode('/', $alias).'/';	
			
			$aliasfull=preg_replace('/\\/\\//', '/', $aliasfull);
			$res = $ItemModel->update($node['id'],array('aliasfull'=>$aliasfull));	
		}
		
	}
	
	public function beforeUpdate($params) {
		return $this->checkMode($params);
	}
	
	public function beforeCreate( $params) {
		return $this->checkMode($params);
	}
	
	private function checkMode($params) {
		if  ( $this->getModel()->getMultilang() ) return $params;
		$mode = $params ['mode'];
		if ($mode != 0) {
			$data = array ('mode' => 0 );
			$pages=new Zend_Db_Table('pages_item');
			$pages->update ( $data, "`mode`=$mode" );
		}
		return ($params);
	}
	
}